package top.vanchor.flexible.utils;

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.font.FontProvider;
import lombok.extern.log4j.Log4j2;
import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import top.vanchor.flexible.config.initexception.BusinessException;
import top.vanchor.flexible.config.initexception.ErrorEnum;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * PDF工具
 *
 * @author ppp
 * @date 2022/8/5
 */
@Log4j2
public class PdfUtil {

    static {
        // Velocity初始化
        Velocity.setProperty(RuntimeConstants.OUTPUT_ENCODING, StandardCharsets.UTF_8);
        Velocity.setProperty(RuntimeConstants.INPUT_ENCODING, StandardCharsets.UTF_8);
        Velocity.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        Velocity.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        Velocity.init();
    }

    /**
     * 据模板生成pdf格式文件
     *
     * @param context      上下文对象
     * @param template     pdf模板
     * @param outputStream 生成pdf文件输出流
     */
    public static void pdfFile(Context context, String template, OutputStream outputStream) {
        PdfDocument pdfDocument = null;
        ByteArrayOutputStream tempStream = new ByteArrayOutputStream();
        String fontSrc;
        String osName = System.getProperty("os.name").toLowerCase();
        log.info("此系统名称为:{}", osName);
        if (osName.contains("windows")) {
            fontSrc = "C:\\Windows\\Fonts\\simsun.ttc,1";
        } else {
            fontSrc = "/usr/share/fonts/simsun.ttc,1";
        }
        try {
            //创建PdfWriter
            PdfWriter pdfWriter = new PdfWriter(tempStream);
            pdfDocument = new PdfDocument(pdfWriter);
            pdfDocument.setDefaultPageSize(PageSize.A4.rotate());

            //创建含边距的文档
            Document document = new Document(pdfDocument);
            document.setMargins(36, 36, 36, 36); // Top, Right, Bottom, Left margins in points

            // 创建ConverterProperties并设置字体
            ConverterProperties properties = new ConverterProperties();
            FontProvider fontProvider = new FontProvider();
            PdfFont sysFont = PdfFontFactory.createFont(fontSrc, PdfEncodings.IDENTITY_H);
            fontProvider.addFont(sysFont.getFontProgram(), PdfEncodings.IDENTITY_H);
//            PdfFont sysFont = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H");
//            fontProvider.addFont(sysFont.getFontProgram(), "UniGB-UCS2-H");
            properties.setFontProvider(fontProvider);

            //处理HTML为PDF
            Template pdfTemplate = Velocity.getTemplate(template, "UTF-8");
            StringWriter writer = new StringWriter();
            pdfTemplate.merge(context, writer);
            HtmlConverter.convertToPdf(writer.toString(), pdfDocument, properties);
            //关闭文档
            document.close();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException("PDF文件生成失败",e);
        } finally {
            if (pdfDocument != null) {
                pdfDocument.close();
            }
        }

        try {
            PdfReader pdfReader = new PdfReader(new ByteArrayInputStream(tempStream.toByteArray()));
            PdfWriter pdfWriter = new PdfWriter(outputStream);
            PdfDocument pdfDocWithPages = new PdfDocument(pdfReader, pdfWriter);

            // 添加页码
            int numberOfPages = pdfDocWithPages.getNumberOfPages();
            PdfFont sysFont = PdfFontFactory.createFont(fontSrc, PdfEncodings.IDENTITY_H);
//            PdfFont sysFont = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H");
            for (int i = 1; i <= numberOfPages; i++) {
                PdfPage page = pdfDocWithPages.getPage(i);
                PdfCanvas canvas = new PdfCanvas(page);
                canvas.beginText()
                        .setFontAndSize(sysFont, 12) // 将字体大小设为10
                        .moveText(page.getPageSize().getWidth() / 2 - 20, 20)
                        .showText(String.format("第  %d / %d  页", i, numberOfPages))
                        .endText();
            }
            pdfDocWithPages.close();
        } catch (Exception e) {
            throw new RuntimeException("添加页码失败", e);
        }
    }
}
